package com.chanven.lib.cptr.loadmore;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * webview滑动监听,并做了其他处理
 */
public class ScrollWebView extends WebView {
    public static final String rule = "^((https|http)?:\\/\\/)(((www|app|global|globalapp|finance)\\.(pearvideo|pearmedia|thegloballyproject|globallyproject|chinabosstory|thebosstory|themoneyconomy)\\.(com|cn)|(139\\.196\\.248\\.170)|(106\\.15\\.131\\.0))|(credit\\.cecdc\\.com))[^\\s]+";

    public ScrollInterface mScrollInterface;
    private View footView;
    private int webViewContentHeight = 0;
    private boolean hasFoot = false;//是否有下拉刷新
    private boolean hasMore = true;//是否还有更多
    private boolean errorFlag = false;//是否加载错误
    private boolean finishFlag = false;//是否加载完成
    private boolean isNeedReload = false;//嵌套在scrollview中,图片有可能无法显示,需要reload一次
    private boolean isReloadOne = true;

    private String hostname = "";

    public ScrollWebView(Context context) {
        super(context);
    }

    public ScrollWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public ScrollWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
//        super.onScrollChanged(l, t, oldl, oldt);
        if (mScrollInterface != null) {
            mScrollInterface.onSChanged(this, l, t, oldl, oldt);
        }
        if (webViewContentHeight != getContentHeight()) {
            webViewContentHeight = getContentHeight();
            updateFootView(hasMore);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        webViewContentHeight = getContentHeight();
    }

    @Override
    public void loadUrl(String url) {
        if (!TextUtils.isEmpty(url) && url.startsWith("http")) {
            if (isNeedReload) {
                isReloadOne = false;
            }
            errorFlag = false;

            URL url1 = null;
            try {
                url1 = new URL(url);
                hostname = url1.getHost();
            } catch (MalformedURLException e) {
                e.printStackTrace();
                hostname = "";
            }
        }
        super.loadUrl(url);
    }

    @Override
    public void reload() {
        errorFlag = false;
        super.reload();
    }

    public void setIsNeedReload(boolean needReload) {
        this.isNeedReload = needReload;
    }

    public void updateFootView() {
        updateFootView(footView);
    }

    /**
     * 更新footview
     */
    public void updateFootView(View footView) {
        if (footView == null) {
            return;
        }
        if (this.footView == null) {
            this.footView = footView;
            addView(this.footView);
        }
        if (this.footView != null) {
            float bottomPadding = this.footView.getMeasuredHeight();
            this.footView.setY(Math.max(webViewContentHeight, getContentHeight()) * getScale() - bottomPadding);
            loadUrl("javascript:bodyBottom(" + bottomPadding / getScale() + ")");
        }
    }

    public void updateFootView(boolean hasMore) {
//        if (!hasFoot) {
//            return;
//        }
        this.hasMore = hasMore;
        updateFootView(footView);
    }

    public boolean isHasFoot() {
        return hasFoot;
    }

    public void setHasFoot(boolean hasFoot) {
        this.hasFoot = hasFoot;
    }

    public boolean isErrorFlag() {
        return errorFlag;
    }

    public boolean isFinishFlag() {
        return finishFlag;
    }

    public void setFootView(View footView) {
        this.footView = footView;
    }

    /**
     * webview默认初始化设置
     */
    public void setWebDefConfig() {

        setVisibility(View.INVISIBLE);
        setWebViewClient(webViewClient);
        setWebChromeClient(webChromeClient);

        addOnLayoutChangeListener(new OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        updateFootView();
                    }
                }, 600);
            }
        });
    }

    private WebViewClient webViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            finishFlag = false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (webFinishList != null && webFinishList.size() > 0) {
                try {
                    for (WebFinish webFinish : webFinishList) {
                        webFinish.webFinishListener(view, url);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            finishFlag = true;

            if (!isReloadOne) {
                isReloadOne = true;
                reload();
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            if(verifyLoadUrl(failingUrl)){
                errorFlag = true;
                if (webErrorList != null && webErrorList.size() > 0) {
                    try {
                        for (WebError webError : webErrorList) {
                            webError.webErrorListener(view);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            try {
                if(verifyLoadUrl(request.getUrl().toString())){
                    errorFlag = true;
                    if (webErrorList != null && webErrorList.size() > 0) {
                        try {
                            for (WebError webError : webErrorList) {
                                webError.webErrorListener(view);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                super.onReceivedError(view, request, error);
            }
        }

//        @Override
//        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
//            WebResourceResponse response =  super.shouldInterceptRequest(view, url);
//            if(interceptRequest != null){
//                return interceptRequest.webInterceptRequest(response, url);
//            }
//            return response;
//        }
//
//        @Override
//        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
//
//            String url = null;
//            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
//                url = request.getUrl().toString();
//            }
//            WebResourceResponse response =  super.shouldInterceptRequest(view, request);
//            if(interceptRequest != null && !TextUtils.isEmpty(url)){
//                return interceptRequest.webInterceptRequest(response, url);
//            }
//            return response;
//        }
    };

    private boolean verifyLoadUrl(String url){
        if(TextUtils.isEmpty(url)){
            return false;
        }
        Pattern r = Pattern.compile(rule);
        Matcher m = r.matcher(url);
        return m.matches();
    }

    private WebChromeClient webChromeClient = new WebChromeClient() {

        @Override
        public boolean onJsAlert(WebView webView, String s, String s1, JsResult jsResult) {
            return super.onJsAlert(webView, s, s1, jsResult);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onCloseWindow(WebView window) {
            super.onCloseWindow(window);
        }
    };

    public void addWebFinishListener(WebFinish webFinish) {
        if (webFinishList == null) {
            webFinishList = new ArrayList<>();
        }
        webFinishList.add(webFinish);
    }

    public void clearFinishListener() {
        webFinishList.clear();
    }

    public void addWebErrorListener(WebError webError) {
        if (webErrorList == null) {
            webErrorList = new ArrayList<>();
        }
        webErrorList.add(webError);
    }

    public void clearErrorListener() {
        webErrorList.clear();
    }

    public InterceptRequest getInterceptRequest() {
        return interceptRequest;
    }

    public void setInterceptRequest(InterceptRequest interceptRequest) {
        this.interceptRequest = interceptRequest;
    }

    /**
     * webview拦截监听
     */
    private InterceptRequest interceptRequest;

    public interface InterceptRequest {
        WebResourceResponse webInterceptRequest(WebResourceResponse response, String url);
    }

    /**
     * webview加载完成监听
     */
    private List<WebFinish> webFinishList;

    public interface WebFinish {
        void webFinishListener(WebView view, String url);
    }

    /**
     * webview加载出错监听
     */
    private List<WebError> webErrorList;

    public interface WebError {
        void webErrorListener(WebView view);
    }

    public void setOnCustomScrollChangeListener(ScrollInterface scrollInterface) {
        this.mScrollInterface = scrollInterface;
    }

    /**
     * webview滑动监听
     */
    public interface ScrollInterface {
        public void onSChanged(ScrollWebView webView, int l, int t, int oldl, int oldt);
    }

    @Override
    public int computeVerticalScrollRange() {
        int computeVerticalScrollRange = super.computeVerticalScrollRange();
        return computeVerticalScrollRange;
    }
}

